// pages/perfectOrder/perfectOrder.js
const orderService = require('../../../../api/orderService.js')
const addressService = require('../../../../api/addressService.js')
const distributionService = require('../../../../api/distributionService.js')
const teamBuyService = require('../../../../api/teamBuyService.js')
const storeService = require('../../../../api/storeService.js')
const advanceSellService = require('../../../../api/advanceSellService.js')
const util = require('../../../../utils/utils.js')
var QQMapWX = require('../../../../libs/qqmap-wx-jssdk.min.js');
var qqmapsdk;
const app = getApp()
const memberService = require('../../../../api/memberService.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: 'selftake',
    date: '2016-09-01',
    time: '12:01',
    multiArray: [
      ['2018-06-01', '2018-06-02', '2018-06-03'],
      ['6:00-9:00', '9:00-12:00', '12:00-15:00', '15:00-18:00', '18:00-21:00']
    ],
    multiIndex: [0, 0],
    addressInfo: '', // 收货地址信息
    goodsList: [], // 商品信息
    allPrice: 0, // 总价
    discount: 0, //购物车优惠金额
    couponPrice: 0, // 优惠券价格
    distance: '', // 配送距离
    remarks: '口味偏好等要求', // 备注
    distributionInfo: {
      distributionFee: 0.00
    }, // 配送信息
    shipmentAmount: 0.00, //配送费
    freeshipCoupon: 0, // 运费优惠
    shipmentDiscount: 0, // 优惠后的运费
    storeName: "人民广场店",
    storeId: '',
    storeTime: [], //营业时间
    storeInfo: {},
    couponTips: '选择优惠券',
    couponInfo: {
      description: '选择优惠券',
      data: {
        freeship: [],
        discount: []
      },
      useCoupon: false
    },
    teamBuyId: '',
    teamLeaderRecordId: '',
    modal: false,
    integralModal: false,
    useReserve: false, //使用储值余额
    cardInfo: {
      useAmount: 0.00, //本次使用额度
      balance: 0.00, //储值卡余额
      password: '', //储值卡密码密码
    },
    cardPassword: '',
    canBuy: true,
    chooseTime: [
      [],
      []
    ],
    memberInfo: {},
    tips: '',
    paddingTop: '0rpx',
    businessStatus: true, //营业状态
    sharingPersonId: '',
    orderType: 'normal', //orderType(模块类型): secondkill(秒杀)  group(拼团)  normal(普通) distribution(统配) advanceSell(预售) scoreMall(积分商城)
    integral: 0,
    scoreArray: [],
    scoreIndex: 0,
    memberScore: 0,
    scoreInfo: {
      scoreAmount: 0
    },
    scoreUseAmount: 0.00,
    advanceSellInfo: {}, //预售相关信息
    teamBuyInfo: {},
    scource: '', //来自购物车SHOPPINGCART,立即购买BUYNOW
    orderSelfTime: ''
  },

  // 顶部类型点击事件
  handleClick: function (val) {
    if (val.currentTarget.dataset.type === 'dispatch') {
      this.setData({
        type: 'dispatch',
      })
      this.checkDistribution()
      this.handleCardBalance()
      if (this.data.orderType !== 'advanceSell') {
        this.checkProductsSellTime()
      }
    } else {
      this.setData({
        type: 'selftake',
        canBuy: true,
        shipmentAmount: 0,
        shipmentDiscount: 0,
        freeshipCoupon: 0
      })
      this.handleCardBalance()
      if (this.data.orderType !== 'advanceSell') {
        this.checkProductsSellTime()
      }
    }
    this.setData({
      couponPrice: 0,
      couponInfo: {
        description: '选择优惠券',
        data: [],
        useCoupon: false
      },
    })
  },
  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
  },
  bindMultiPickerColumnChange: function (e) {
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    var now = new Date();
    let tempStart = this.data.storeTime[0] + ':00'
    let tempEnd = this.data.storeTime[1] + ':00'
    let date = util.formatTime(now).split(" ")[0]
    var startTimeDetails = new Date(date + " " + tempStart).getTime()
    var endTimeDetails = new Date(date + " " + tempEnd).getTime()
    var nowTime = new Date(util.formatTime(now)).getTime()
    switch (data.multiIndex[0]) {
      case 0:
        if (nowTime < endTimeDetails && nowTime > startTimeDetails) {
          data.multiArray[1] = this.data.chooseTime[1]
        }
        break;
      case 1:
        data.multiArray[1] = this.data.chooseTime[0];
        break;
      case 2:
        data.multiArray[1] = this.data.chooseTime[0];
        break;
    }
    if (data.multiArray[1][0] === '请选择其他时间' || data.multiArray[1][0] === '不能下单') {
      this.setData({
        canBuy: false
      });
    } else {
      this.setData({
        canBuy: true
      });
    }
    this.setData(data);
  },
  //初始化预约时间
  initializationTime: function () {
    const self = this
    var now = new Date();
    var hour = now.getHours(); //小时数
    let days = 3
    var tempTime = [
      [],
      []
    ]
    var groupEndTime = self.data.teamBuyInfo.endTime
    var orderSelfScope = self.data.teamBuyInfo.orderSelfScope
    var groupTime = []
    if (self.data.orderType === 'advanceSell') {
      let advanceSellInfo = self.data.advanceSellInfo
      if (advanceSellInfo.payType === 'FULL') {
        const endTime = new Date(util.formatTime(now)).getTime()
        const tempEndTime = util.formatTime(self.addDay(endTime, advanceSellInfo.deliveryTime))
        now = new Date(tempEndTime).getTime()
        console.log(now, '123')
      } else if (advanceSellInfo.payType === 'PARTIAL') {
        const endTime = new Date(advanceSellInfo.balanceEndTime.replace(/-/g, '/')).getTime()
        const tempEndTime = util.formatTime(self.addDay(endTime, advanceSellInfo.deliveryTime))
        now = new Date(tempEndTime).getTime()
      }
    }
    //  else if (self.data.orderType === 'group') {
    //   groupTime = groupEndTime.split(" ")
    //   console.log(groupTime)
    // }
    if (self.data.orderType === 'group') {
      groupTime = orderSelfScope.split(" ")
      let daysArr = groupTime[0].split("-")
      let timeArr = groupTime[1].split("-")
      let startDate = daysArr[0].split(":")
      let endDate = daysArr[1].split(":")
      let day = startDate[1] + '月' + startDate[2] + '日-' + endDate[1] + '月' + endDate[2] + '日'
      let time = timeArr[0].slice(0, 5) + '-' + timeArr[1].slice(0, 5)
      let orderSelfTime = day + ' ' + time
      console.log(orderSelfTime)
      self.setData({
        orderSelfTime: orderSelfTime
      })
    } else {
      for (let i = 0; i < days; i++) {
        let date = self.addDay(now, i)
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        let newDate = [year, month, day].map(util.timeFormat).join('-')
        tempTime[0].push(newDate)
      }
      tempTime[1] = self.handleChooseTime()
      self.setData({
        multiArray: tempTime,
      })
    }
  },
  getStoreInfoById: function (id) {
    const that = this
    storeService.getById(id).then(res => {
      console.log(res)
      const storeInfo = res
      let storeTime = storeInfo.storeHours.split("-")
      that.setData({
        storeTime: storeTime
      })
    })
  },
  handleChooseTime: function () {
    const self = this
    var now = new Date();
    var hour = now.getHours(); //小时数
    var minute = now.getMinutes(); //分钟数
    var time = [hour, minute].map(util.timeFormat).join(':')
    let storeTime = ''
    let tempTime = []
    var businessHours = []
    // 处理经营时间
    try {
      var allStores = wx.getStorageSync('wj_allStores')
      console.log(this.data.storeId)
      var reg = new RegExp(this.data.storeId);
      if (allStores) {
        allStores.forEach(item => {
          if (reg.test(item.id)) {
            storeTime = item.storeHours.split("-")
          }
        })
      }
    } catch (e) {}
    console.log(storeTime)
    let tempStart = storeTime[0] + ':00'
    let tempEnd = storeTime[1] + ':00'
    let date = util.formatTime(now).split(" ")[0]
    var startTimeDetails = new Date(date + " " + tempStart).getTime()
    var endTimeDetails = new Date(date + " " + tempEnd).getTime()
    var nowTime = new Date(util.formatTime(now)).getTime()
    businessHours = this.splitTime(date, date, 10800000, tempStart, tempEnd);
    let hourArray = [] //营业时间小时数组
    businessHours.forEach(ele => {
      hourArray.push(ele.slice(0, 2))
    });
    let hourArrayLength = hourArray.length
    console.log(businessHours)
    let chooseTime = [
      [],
      []
    ]
    for (let j = 0; j < businessHours.length - 1; j++) {
      const eleStart = businessHours[j];
      const eleEnd = businessHours[j + 1];
      let tempData = eleStart + '-' + eleEnd
      chooseTime[0].push(tempData)
    }
    for (let i = 0; i < hourArray.length; i++) {
      if (hour >= hourArray[i] && hour < hourArray[i + 1]) {
        chooseTime[1].push(time + '-' + businessHours[i + 1])
        for (let k = i + 1; k < businessHours.length - 1; k++) {
          const eleStart = businessHours[k];
          const eleEnd = businessHours[k + 1];
          let tempData = eleStart + '-' + eleEnd
          chooseTime[1].push(tempData)
        }
      }
    }
    self.setData({
      chooseTime: chooseTime,
      storeTime: storeTime
    })
    console.log(hourArray[hourArrayLength - 1])
    // 小时
    if (nowTime < startTimeDetails || nowTime < endTimeDetails) {
      tempTime = chooseTime[1];
    } else {
      tempTime = chooseTime[0]
    }
    if (self.data.orderType === 'advanceSell') {
      // 预售
      tempTime = chooseTime[0]
    }
    console.log(tempTime)
    return tempTime
  },
  /**
   * 通过营业时间进行计算返回3小时间隔的时间数组
   * @param startDate 起始时间 xxxx/xx/xx
   * @param endDate 结束时间 xxxx/xx/xx
   * @param amount 时间间隔 毫秒
   */
  splitTime: function (startDate, endDate, amount, timeStart, timeEnd) {
    var startTime = new Date(startDate + " " + timeStart)
    var endTime = new Date(endDate + " " + timeEnd)
    var gap = amount;
    let count = Math.ceil((endTime - startTime) / gap)
    let realCount = (endTime - startTime) / gap
    console.log(count)
    var temp = [];
    let tempTime = []
    if (count - realCount >= 0) {
      temp.push(util.formatTime(startTime))
      for (var i = 1; i < count; i++) {
        startTime.setMilliseconds(startTime.getMilliseconds() + gap);
        temp[i] = util.formatTime(new Date(startTime.getTime()));
      }
      temp.push(util.formatTime(endTime))
    } else {
      temp.push(util.formatTime(startTime))
      for (var i = 1; i < count; i++) {
        startTime.setMilliseconds(startTime.getMilliseconds() + gap);
        temp[i] = util.formatTime(new Date(startTime.getTime()));
      }
    }
    temp.forEach(item => {
      let tempData = item.split(" ")[1].slice(0, 5);
      tempTime.push(tempData)
    });
    tempTime = Array.from(new Set(tempTime))
    return tempTime;
  },
  addDay: function (curDate, days) {
    return new Date((curDate / 1000 + (86400 * days)) * 1000)
  },
  // 跳转到选择地址页面
  toChooseAddress: function () {
    wx.navigateTo({
      url: '../../member/address/addressList/addressList?from=perfectOrder'
    })
  },
  // 添加备注
  addRemarks: function (e) {
    console.log(e)
    wx.navigateTo({
      url: '../addRemarks/addRemarks?type=' + this.data.type
    })
  },
  getPostData: function () {
    const that = this
    let products = [];
    this.data.goodsList.forEach(item => {
      let tempItem = {
        productId: item.productId,
        productNum: item.productNum
      }
      if (that.data.scource === 'SHOPPINGCART') {
        tempItem = {
          ...tempItem,
          shoppingCartItemId: item.id
        }
      }
      if (item.newmbrActivityId) {
        tempItem = {
          ...tempItem,
          newmbrActivityId: item.newmbrActivityId
        }
        products.push(tempItem)
      } else if (item.grabActivityId) {
        tempItem = {
          ...tempItem,
          activityId: item.grabActivityId
        }
        products.push(tempItem)
      } else {
        products.push(tempItem)
      }
    })
    var postData = '';
    var tempSelfTime = null;
    let shipmentType = 'self';
    let tempShipAmount = 0;
    const distributionInfo = that.data.distributionInfo
    const freeshipDiscount = that.data.freeshipCoupon
    if (this.data.type === 'dispatch') {
      shipmentType = 'EXPRESS';
      if (distributionInfo.distributioCompany === "DEFAULT") {
        tempShipAmount = distributionInfo.baseFare
      } else {
        tempShipAmount = distributionInfo.distributionFee
      }
      let tempFreeship = tempShipAmount - freeshipDiscount
      that.setData({
        shipmentDiscount: tempFreeship.toFixed(2),
      })
    } else {
      shipmentType = 'SELF';
      if (that.data.orderType === 'group') {
        tempSelfTime = ''
      } else {
        tempSelfTime = that.data.multiArray[0][that.data.multiIndex[0]] + ' ' + that.data.multiArray[1][that.data.multiIndex[1]];
      }
    }
    let paymentPrice = parseFloat(this.data.allPrice - this.data.couponPrice + tempShipAmount)
    if (paymentPrice >= 0) {
      paymentPrice = paymentPrice.toFixed(2)
    } else {
      paymentPrice = 0
    }

    let couponData = []
    let externalCouponData = ''
    if (that.data.couponInfo.useCoupon) {
      if (that.data.couponInfo.data.discount && that.data.couponInfo.data.discount.length > 0) {
        that.data.couponInfo.data.discount.forEach(item => {
          if (item.service === 'GM') {
            couponData.push(item.coupon.cardNum)
          } else if (item.service === 'HD') {
            externalCouponData = item.coupon.cardNum
          }
        })
      }
      if (that.data.couponInfo.data.freeship && that.data.couponInfo.data.freeship.length > 0) {
        that.data.couponInfo.data.freeship.forEach(item => {
          if (item.service === 'GM') {
            couponData.push(item.coupon.cardNum)
          } else if (item.service === 'HD') {
            externalCouponData = item.coupon.cardNum
          }
        })
      }
    }
    console.log(this.data.addressInfo)
    postData = {
      allPrice: paymentPrice, // 应该支付的金额
      products: products, // 商品列表
      receiverMobile: this.data.addressInfo ? this.data.addressInfo.contactsMobile : this.data.memberInfo.mobile, // 收货人手机号
      remark: this.data.remarks === '口味偏好等要求' ? '无' : this.data.remarks, // 备注
      scource: 'SHOPPINGCART', // 来自购物车SHOPPINGCART 立即购买BUYNOW
      shipmentAmount: tempShipAmount, // 快递费
      shipmentType: shipmentType, // 配送方式
      selfTimeScope: tempSelfTime, // 预约自提时间
      storeId: this.data.storeId, // 门店id
      couponIds: couponData, //券Id
      externalCouponNumber: externalCouponData,
      score: that.data.integral,
      orderSource: 'MINI_APP'
    }
    console.log(shipmentType)
    if (shipmentType === 'EXPRESS') {
      if (this.data.addressInfo) {
        postData = {
          ...postData,
          deliveryAddressId: this.data.addressInfo.id, // 收货地址id
          distributionDistance: this.data.distance, // 配送距离
        }
      } else {
        // wx.showToast({
        //   title: '请选择收货地址~',
        //   icon: 'none',
        //   duration: 2000
        // })
      }
    }
    // 如果是团购
    if (this.data.orderType === 'group') {
      postData = {
        ...postData,
        teamBuyingId: this.data.teamBuyId,
        teamLeaderRecordId: this.data.teamLeaderRecordId,
        scource: that.data.scource
      }
    } else if (this.data.orderType === 'secondkill') {
      //如果是秒杀
      let productData = []
      that.data.goodsList.forEach(item => {
        console.log(item)
        if (item.activityId) {
          productData.push({
            activityId: item.activityId,
            productId: item.productId,
            productNum: item.productNum
          })
        } else {
          productData.push({
            productId: item.productId,
            productNum: item.productNum
          })
        }
      })
      postData = {
        ...postData,
        products: productData,
        scource: 'BUYNOW', //抢购默认秒杀
      }
      if (that.data.scource === 'SHOPPINGCART') {
        postData = {
          ...postData,
          scource: 'SHOPPINGCART',
        }
      }
    } else if (this.data.orderType === 'advanceSell') {
      //如果是预售
      let productData = []
      let balanceTotal = 0
      that.data.goodsList.forEach(item => {
        console.log(item)
        if (item.advanceId) {
          productData.push({
            advanceId: item.advanceId,
            balanceTotal: item.balanceTotal,
            productId: item.productId,
            productNum: item.productNum
          })
          balanceTotal = item.balanceTotal
        } else {
          productData.push({
            productId: item.productId,
            productNum: item.productNum
          })
        }
      })
      postData = {
        ...postData,
        balanceTotal: balanceTotal,
        products: productData,
        scource: 'BUYNOW',
      }
    }
    // 如果选择使用储值卡
    if (this.data.useReserve) {
      postData = {
        ...postData,
        allPrice: paymentPrice - this.data.cardInfo.useAmount,
        cardAmount: this.data.cardInfo.useAmount, //储值卡支付金额
        cardPassword: this.data.cardInfo.password, //储值卡密码
      }
    }
    console.log(app.globalData.userInfo.member.id)
    // 如果通过分享
    if (this.data.sharingPersonId && this.data.sharingPersonId !== app.globalData.userInfo.member.id) {
      let productData = []
      postData.products.forEach(item => {
        productData.push({
          ...item,
          sharingPersonId: that.data.sharingPersonId,
        })
      })
      postData = {
        ...postData,
        orderSource: 'SHARE',
        products: productData,
      }
    }
    return postData;
  },
  // 创建订单
  createOrder: function (val) {
    const self = this
    let postData = this.getPostData();
    var deliveryStatus = true
    console.log(postData)
    try {
      // 清除部分缓存数据，以免对其他订单造成影响
      wx.removeStorageSync('wj_orderCardInfo')
      wx.removeStorageSync('wj_addRemarks')
    } catch (e) {}
    if (postData.shipmentType === 'EXPRESS') {
      if (!postData.deliveryAddressId) {
        deliveryStatus = false
      } else {
        deliveryStatus = true
      }
    }
    let orderType = this.data.orderType
    if (deliveryStatus) {
      if (self.data.canBuy) {
        this.setData({
          canBuy: false
        })
        try {
          wx.setStorageSync('wj_wxa_formId', val.detail.formId)
        } catch (e) {}
        if (orderType === 'group') {
          teamBuyService.createOrder(postData).then(res => {
            console.log(res)
            self.clearCacheData()
            // self.getPay(res)
            self.toPayMethod(res.id, 'normal')
          }).catch(err => {
            if (err.code === 16001) {
              wx.showToast({
                title: '商品暂未上架，请到别的门店看看吧！',
                icon: 'none',
                duration: 2000
              })
            } else {
              wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            }
            self.setData({
              canBuy: true
            })
          })
        } else if (orderType === 'advanceSell') {
          // 预售
          console.log(postData)
          advanceSellService.createOrder(postData).then(res => {
            console.log(res)
            self.clearCacheData()
            // self.getPay(res)
            self.toPayMethod(res.id, 'normal')
          }).catch(err => {
            if (err.code === 16001) {
              wx.showToast({
                title: '商品暂未上架，请到别的门店看看吧！',
                icon: 'none',
                duration: 2000
              })
            } else {
              wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            }
            self.setData({
              canBuy: true
            })
          })
        } else if (orderType === 'scoreMall') {
          orderService.createScoreOrder(postData).then(res => {
            console.log(res)
            self.clearCacheData()
            if (res.shipmentAmount === 0) {
              // 无运费
              self.getPay(res)
            } else {
              self.toPayMethod(res.id, 'normal')
            }
          }).catch(err => {
            console.log(err)
            if (err.code === 14009) {
              // 门店已经暂停线上下单
              self.getAllStore()
              wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            } else if (err.code === 16001) {
              wx.showToast({
                title: '商品暂未上架，请到别的门店看看吧！',
                icon: 'none',
                duration: 2000
              })
            } else {
              wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            }
            self.setData({
              canBuy: true
            })
          })
        } else {
          orderService.createCatering(postData).then(res => {
            console.log(res)
            self.clearCacheData()
            // self.getPay(res)
            self.toPayMethod(res.id, 'normal')
          }).catch(err => {
            console.log(err)
            if (err.code === 14009) {
              // 门店已经暂停线上下单
              self.getAllStore()
              wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            } else if (err.code === 16001) {
              wx.showToast({
                title: '商品暂未上架，请到别的门店看看吧！',
                icon: 'none',
                duration: 2000
              })
            } else {
              wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            }
            self.setData({
              canBuy: true
            })
          })
        }
      }
    } else {
      wx.showToast({
        title: '收货地址不能为空~',
        icon: 'none',
        duration: 2000
      })
    }
  },

  /**
   * 提交订单
   * 并不会实际创建订单
   * 需要选择支付方式去支付时或离开支付页面才会创建订单
   */
  submitOrder: function (val) {
    const self = this
    let postData = this.getPostData();
    var deliveryStatus = true
    var selfTime = true
    console.log(postData)
    try {
      // 清除部分缓存数据，以免对其他订单造成影响
      wx.removeStorageSync('wj_orderCardInfo')
      wx.removeStorageSync('wj_addRemarks')
    } catch (e) {}
    if (postData.shipmentType === 'EXPRESS') {
      if (!postData.deliveryAddressId) {
        deliveryStatus = false
      } else {
        deliveryStatus = true
      }
    } else {
      if (!postData.selfTimeScope) {
        selfTime = false
      } else {
        selfTime = true
      }
    }
    let orderType = this.data.orderType
    if (deliveryStatus) {
      if (selfTime) {
        if (self.data.canBuy) {
          this.setData({
            canBuy: false
          })
          try {
            let orderData = {
              data: postData,
              formId: val.detail.formId,
              orderType: self.data.orderType
            }
            wx.setStorageSync('wj_orderDetails', orderData)
            self.toPayMethod('normal')
          } catch (error) {
            console.log(error)
          }
        }
      } else {
        wx.showToast({
          title: '自提时间不能为空~',
          icon: 'none',
          duration: 2000
        })
      }
    } else {
      wx.showToast({
        title: '收货地址不能为空~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 前往支付页面
  toPayMethod: function (orderId, type) {
    wx.redirectTo({
      url: '../../pay/payMethod/payMethod?orderId=' + orderId + '&from=shopCart&type=' + type
    })
  },
  // 刷新所有门店
  getAllStore: function () {
    const self = this
    storeService.queryList().then(res => {
      var allStores = [];
      res.forEach(item => {
        if (item.status === 'OPEN') {
          allStores.push(item)
        }
      });
      try {
        wx.setStorageSync('wj_allStores', allStores)
        wx.getLocation({
          type: 'wgs84',
          success: function (res) {
            var latitude = res.latitude
            var longitude = res.longitude
            let tempIndex = self.getNearestStore(allStores, latitude, longitude);
            app.globalData.storeInfo = allStores[tempIndex];
            self.setData({
              storeName: app.globalData.storeInfo.name,
              storeId: app.globalData.storeInfo.id,
              storeInfo: app.globalData.storeInfo
            })
          },
          fail: function (res) {
            console.log(res)
          }
        })
      } catch (e) {
        console.log(e)
      }
    })
  },
  // 获取最近的一家门店
  getNearestStore: function (allStores, latitude, longitude) {
    var distanceArr = [];
    allStores.forEach(item => {
      let dis = util.distance(latitude, longitude, item.latitude, item.longitude);
      distanceArr.push(dis);
    })
    // 计算最小值
    const minN = Math.min.apply(Math, distanceArr);
    let tempIndex = 0;
    for (var i = 0; i < distanceArr.length; i++) {
      if (minN === distanceArr[i]) {
        tempIndex = i;
        break;
      }
    }
    this.setData({
      store: allStores[tempIndex].name,
      storeId: allStores[tempIndex].id
    })
    return tempIndex;
  },
  clearCacheData: function () {
    try {
      wx.removeStorageSync('wj_sharingId')
    } catch (e) {}
  },
  getPay: function (order) {
    const self = this
    let tempData = {
      orderId: order.id,
      // payMethod: 'SWIFTPASS'
      payMethod: 'WX_MINI_APP'
    }
    if (order.cashTotal === 0) {
      self.toPaymentSuccess(order.id)
    } else {
      orderService.getPaySign(tempData).then(res => {
        var resData = JSON.parse(res);
        var sign = JSON.parse(resData.sign)
        // console.log(resData)
        console.log(sign)
        console.log(sign.paySign)
        let packageValue = ''
        if (tempData.payMethod === 'SWIFTPASS') {
          packageValue = sign.package
        } else if (tempData.payMethod === 'WX_MINI_APP') {
          packageValue = sign.packageValue
        }
        wx.requestPayment({
          'timeStamp': sign.timeStamp,
          'nonceStr': sign.nonceStr,
          'package': packageValue,
          'signType': sign.signType,
          'paySign': sign.paySign,
          'success': function (res) {
            let orderId = tempData.orderId
            self.toPaymentSuccess(orderId)
          },
          'fail': function (res) {
            console.log('支付失败')
            console.log(res)
            if (res.errMsg === 'requestPayment:fail cancel') {
              wx.showToast({
                title: '您取消了订单支付~',
                icon: 'none',
                duration: 2000
              })
              wx.switchTab({
                url: '../../goods/shopcart/shopcart'
              })
            } else {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
              wx.switchTab({
                url: '../../goods/shopcart/shopcart'
              })
            }
          }
        })
      }).catch(err => {
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000
        })
      })
    }
  },
  // 获取配送相关信息
  calcDistance: function (chooseAddress) {
    var self = this;
    var distance = util.distance(chooseAddress.latitude, chooseAddress.longitude, self.data.storeInfo.latitude, self.data.storeInfo.longitude);
    distance = (distance * 1000).toFixed(2);
    console.log(distance)

    this.setData({
      distance: distance
    })
    let address = chooseAddress.province + chooseAddress.city + chooseAddress.county + chooseAddress.detailedAddress + chooseAddress.houseNum
    var postData = {
      address: address,
      distance: Number(distance),
      latitude: chooseAddress.latitude,
      longitude: chooseAddress.longitude,
      positionSource: 1,
      storeId: this.data.storeId
    }
    addressService.checkDelivery(postData).then(res => {
      console.log(res)
      let storeId = this.data.storeId
      if (res.isSuccess || self.data.orderType === 'distribution') {
        distributionService.getDistributionFee(storeId, parseInt(distance)).then(res => {
          console.log(res)
          self.setData({
            distributionInfo: {
              baseFare: res.baseFare,
              distributioCompany: res.distributioCompany,
              distributionFee: res.distributionFee ? res.distributionFee : 0.00,
              freeFare: res.freeFare
            },
          })
          if (self.data.tips === '') {
            self.setData({
              canBuy: true
            })
          } else {}
          let tempShipAmount = 0
          let tempDiscount = self.data.freeshipCoupon
          if (self.data.type === 'dispatch') {
            if (res.distributioCompany === "DEFAULT") {
              tempShipAmount = res.baseFare
            } else {
              tempShipAmount = res.distributionFee
            }
            console.log("配送")
            let tempData = 0
            tempData = parseFloat((tempShipAmount - tempDiscount).toFixed(2))
            self.setData({
              shipmentAmount: tempShipAmount,
              shipmentDiscount: tempData
            })
          }
        }).catch(err => {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000
          })
        })
      } else {
        if (self.data.orderType !== 'distribution' && self.data.orderType !== 'advanceSell') {
          wx.showToast({
            title: '该地址超出配送范围，请重新修改收货地址~',
            icon: 'none',
            duration: 2000
          })
          self.setData({
            canBuy: false
          })
        } else {
          self.setData({
            canBuy: true
          })
        }
      }
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
      if (self.data.orderType !== 'distribution' && self.data.orderType !== 'advanceSell') {
        wx.showToast({
          title: '门店暂不支持配送~',
          icon: 'none',
          duration: 2000
        })
        self.setData({
          canBuy: false
        })
      } else {
        self.setData({
          canBuy: true
        })
      }
    })
  },

  // 去选择优惠券
  toChoiceCoupon: function (val) {
    const that = this
    let orderData = JSON.stringify(this.getPostData());
    console.log(this.data.integral)
    if (this.data.integral > 0) {
      wx.showModal({
        title: '提示',
        content: '积分和优惠券不可同时使用',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            that.setData({
              integral: 0,
              scoreInfo: {
                scoreAmount: 0
              },
            })
            orderData = JSON.stringify(that.getPostData());
            wx.navigateTo({
              url: '../../coupon/choiceCoupon/choiceCoupon?orderData=' + orderData + '&type=' + that.data.type + '&orderType=' + that.data.orderType
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      wx.navigateTo({
        url: '../../coupon/choiceCoupon/choiceCoupon?orderData=' + orderData + '&type=' + that.data.type + '&orderType=' + that.data.orderType + '&couponType=' + val.currentTarget.dataset.type
      })
    }
  },
  // 支付成功
  toPaymentSuccess: function (orderId) {
    wx.navigateTo({
      url: '../../pay/payment/payment?orderId=' + orderId
    })
  },
  // 操作储值余额
  handleReserve: function (e) {
    const that = this
    if (e.detail.value) {
      this.setData({
        modal: true,
        cardInfo: {
          ...that.data.cardInfo,
          password: '', //储值卡密码
          useAmount: 0
        },
      })
      // 获取储值卡余额
      that.getMbrBalance()
    } else {
      this.setData({
        useReserve: false,
        cardInfo: {
          ...that.data.cardInfo,
          password: '', //储值卡密码
          useAmount: 0
        },
      })
      try {
        wx.removeStorageSync('wj_orderCardInfo')
      } catch (error) {

      }
    }
  },
  // 处理储值卡密码
  handleCardPassword: function (e) {
    const that = this
    this.setData({
      cardInfo: {
        ...that.data.cardInfo,
        password: e.detail.value, //储值卡密码
      },
    })
  },
  // 取消
  onCancel: function () {
    if (this.data.modal) {
      // 取消使用储值卡余额
      this.setData({
        modal: false,
        useReserve: false,
        cardInfo: {
          ...this.data.cardInfo,
          useAmount: 0
        },
      })
      try {
        wx.removeStorageSync('wj_orderCardInfo')
      } catch (error) {

      }
    } else if (this.data.integralModal) {
      // 取消使用积分抵扣
      this.setData({
        integralModal: false,
      })
    }
  },
  // 确认
  onConfirm: function () {
    const that = this
    if (that.data.modal) {
      // 确认使用储值卡余额
      that.setData({
        modal: false,
        useReserve: true
      })
      try {
        let orderCardInfo = {
          ...that.data.cardInfo,
          useReserve: true
        }
        wx.setStorageSync('wj_orderCardInfo', orderCardInfo)
      } catch (e) {

      }
    } else if (that.data.integralModal) {
      // 确认使用积分抵扣
      let useAmount = that.data.scoreUseAmount
      if (useAmount === 0) {
        // 处理默认情况
        let index = that.data.scoreIndex
        useAmount = that.data.scoreArray[index]
      }
      that.setData({
        integralModal: false,
        integral: useAmount
      })
    }
  },
  // 重置密码
  handleResetPassword: function () {
    wx.navigateTo({
      url: '../../myCard/resetPassword/resetPassword'
    })
  },
  // 获取储值卡余额
  getMbrBalance: function () {
    const that = this;
    memberService.getMbrBalance().then(res => {
      this.setData({
        cardInfo: {
          ...that.data.cardInfo,
          balance: res, //储值卡余额
        },
      })
      let allPrice = that.data.allPrice
      let couponPrice = that.data.couponPrice
      let shipmentAmount = that.data.shipmentAmount - that.data.freeshipCoupon
      // let shipmentAmount = that.data.shipmentAmount
      let canUseAmount = that.data.cardInfo.balance
      let tempPrice = parseFloat((allPrice - couponPrice).toFixed(2))
      if (that.data.type === 'dispatch') {
        tempPrice = parseFloat((tempPrice + shipmentAmount).toFixed(2))
      }
      // paymentPrice
      console.log(canUseAmount, tempPrice, shipmentAmount)
      if (tempPrice >= 0) {
        if (tempPrice > canUseAmount) {
          console.log("1")
          this.setData({
            cardInfo: {
              ...that.data.cardInfo,
              useAmount: canUseAmount, //本次使用余额
            },
          })
        } else {
          console.log("2")
          this.setData({
            cardInfo: {
              ...that.data.cardInfo,
              useAmount: tempPrice, //本次使用余额
            },
          })
        }
      } else {
        this.setData({
          cardInfo: {
            ...that.data.cardInfo,
            useAmount: 0, //本次使用余额
          },
        })
      }
    })
  },
  // 切换配送方式时对储值卡余额进行操作
  handleCardBalance: function () {
    this.setData({
      useReserve: false, //使用储值余额
      cardInfo: {
        useAmount: 0.00, //本次使用额度
        balance: 0.00, //储值卡余额
        password: '', //储值卡密码
      },
    })
  },
  // 检查配送
  checkDistribution: function () {
    const that = this
    try {
      var value = wx.getStorageSync('wj_chooseAddressInfo')
      if (value) {
        // 缓存中有默认地址
        this.setData({
          addressInfo: value
        })
        if (that.data.orderType !== 'advanceSell') {
          // 预售不计算运费
          this.calcDistance(value);
        }
      } else {
        // 缓存中没有默认地址
        console.log("123")
        if (that.data.addressInfo == '') {
          console.log("456")
          // 当前没有选择地址
          addressService.getDefaultAddress().then(res => {
            console.log(res)
            if (res) {
              // 有默认地址
              this.setData({
                addressInfo: res
              })
              wx.setStorage({
                key: "wj_chooseAddressInfo",
                data: res
              })
              if (that.data.orderType !== 'advanceSell') {
                // 预售不计算运费
                this.calcDistance(res);
              }
            } else {
              // 无默认地址
              wx.getLocation({
                type: 'wgs84',
                success: function (res) {
                  var latitude = res.latitude
                  var longitude = res.longitude
                  // 查询所有地址
                  addressService.query().then(result => {
                    console.log(result)
                    if (result.length > 0) {
                      let allAddress = result
                      let tempIndex = that.getNearestAddress(allAddress, latitude, longitude)
                      wx.setStorage({
                        key: "wj_chooseAddressInfo",
                        data: allAddress[tempIndex]
                      })
                      that.setData({
                        addressInfo: allAddress[tempIndex]
                      })
                      if (that.data.orderType !== 'advanceSell') {
                        // 预售不计算运费
                        that.calcDistance(allAddress[tempIndex]);
                      }
                    } else {
                      wx.showToast({
                        title: '请选择收货地址~',
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  }).catch(err => {
                    wx.showToast({
                      title: err.message,
                      icon: 'none',
                      duration: 2000
                    })
                  })
                }
              })
            }
          }).catch(err => {
            wx.showToast({
              title: err.message,
              icon: 'none',
              duration: 2000
            })
          })
        } else {
          // 当前选择了地址
          // 查询所有地址
          addressService.query().then(result => {
            console.log(result)
            if (result.length > 0) {
              wx.getLocation({
                type: 'wgs84',
                success: function (res) {
                  var latitude = res.latitude
                  var longitude = res.longitude
                  let allAddress = result
                  let tempIndex = that.getNearestAddress(allAddress, latitude, longitude)
                  // 缓存最近的地址
                  wx.setStorage({
                    key: "wj_chooseAddressInfo",
                    data: allAddress[tempIndex]
                  })
                  that.setData({
                    addressInfo: allAddress[tempIndex]
                  })
                  if (that.data.orderType !== 'advanceSell') {
                    // 预售不计算运费
                    that.calcDistance(allAddress[tempIndex]);
                  }

                }
              })
            } else {
              that.setData({
                addressInfo: ''
              })
              wx.showToast({
                title: '请选择收货地址~',
                icon: 'none',
                duration: 2000
              })
            }
          }).catch(err => {
            wx.showToast({
              title: err.message,
              icon: 'none',
              duration: 2000
            })
          })
        }
      }
    } catch (error) {
      wx.showToast({
        title: error.message,
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 获取最近的一个收货地址
  getNearestAddress: function (allAddress, latitude, longitude) {
    var distanceArr = [];
    allAddress.forEach(item => {
      let dis = util.distance(latitude, longitude, item.latitude, item.longitude);
      distanceArr.push(dis);
    })
    // 计算最小值
    const minN = Math.min.apply(Math, distanceArr);
    let tempIndex = 0;
    for (var i = 0; i < distanceArr.length; i++) {
      if (minN === distanceArr[i]) {
        tempIndex = i;
        break;
      }
    }
    return tempIndex;
  },
  /**
   * 检查商品售卖时间
   * 只要订单中有不在销售时间内的，就只能预约明后两天，今天的不能预约
   * 打烊后只能预约明后两天
   */
  checkProductsSellTime: function () {
    const that = this
    const productsList = that.data.goodsList
    const type = that.data.type
    let tempProducts = []
    let tempAllProducts = []
    let storeTime = []
    // 处理商店营业时间
    try {
      var allStores = wx.getStorageSync('wj_allStores')
      console.log(this.data.storeId)
      var reg = new RegExp(this.data.storeId);
      if (allStores) {
        allStores.forEach(item => {
          if (reg.test(item.id)) {
            storeTime = item.storeHours.split("-")
          }
        })
      }
    } catch (e) {}
    console.log(storeTime)
    let tempStart = storeTime[0] + ':00'
    let tempEnd = storeTime[1] + ':00'
    const now = new Date()
    var hour = now.getHours(); //小时数
    var minute = now.getMinutes(); //分钟数
    var time = [hour, minute].map(util.timeFormat).join(':')
    let date = util.formatTime(now).split(" ")[0]
    var startTimeDetails = new Date(date + " " + tempStart).getTime()
    var endTimeDetails = new Date(date + " " + tempEnd).getTime()
    var nowTime = new Date(util.formatTime(now)).getTime()
    let tempTime = [
      [],
      []
    ]
    productsList.forEach(item => {
      if (item.startTime && item.endTime) {
        let startTime = item.startTime.split(" ")[1].slice(0, 5) + ':00'
        let endTime = item.endTime.split(" ")[1].slice(0, 5) + ':00'
        let newStartTime = new Date(date + " " + startTime).getTime()
        let newEndTime = new Date(date + " " + endTime).getTime()
        if ((nowTime >= startTimeDetails && nowTime <= endTimeDetails) && (nowTime >= newStartTime && nowTime <= newEndTime)) {
          //在商店营业时间和商品售卖时间之内，可以购买
          let tempItem = {
            ...item,
            newStartTime: startTime,
            newEndTime: endTime,
            newStartTimeStamp: newStartTime,
            newEndTimeStamp: newEndTime,
            businessStatus: true
          }
          tempAllProducts.push(tempItem)
        } else {
          let tempItem = {
            ...item,
            newStartTime: startTime,
            newEndTime: endTime,
            newStartTimeStamp: newStartTime,
            newEndTimeStamp: newEndTime,
            businessStatus: false
          }
          tempProducts.push(tempItem)
          tempAllProducts.push(tempItem)
        }
      } else {
        // 商品没有售卖时间默认为门店营业时间
        let tempItem = {
          ...item,
          newStartTime: tempStart,
          newEndTime: tempEnd,
          newStartTimeStamp: startTimeDetails,
          newEndTimeStamp: endTimeDetails,
          businessStatus: true
        }
        tempAllProducts.push(tempItem)
      }
    });
    that.setData({
      goodsList: tempAllProducts
    })
    if (nowTime < startTimeDetails || nowTime > endTimeDetails) {
      let tips = '商店已打烊，不支持配送，请选择自提~'
      console.log(tips)
      that.setData({
        canBuy: false,
        tips: tips,
        paddingTop: '60rpx',
        businessStatus: false
      })
    }
    if (tempProducts.length > 0) {
      let tips = '订单中有商品超出售卖时间~'
      that.setData({
        canBuy: false,
        tips: tips,
        paddingTop: '60rpx',
        businessStatus: true
      })
    }
    if (tempAllProducts.length > 0) {
      if (tempProducts.length > 0) {
        let tips = '订单中有商品超出售卖时间~'
        that.setData({
          canBuy: false,
          tips: tips,
          paddingTop: '60rpx'
        })
      }
      console.log(tempProducts)
      // 根据商品售卖时间重置预约时间
      /**
       * 1、多个找交集
       * 2、没有交集就不可预约
       */
      let tempStartTime = ''
      let tempEndTime = ''
      let tempStartTimeStamp = ''
      let tempEndTimeStamp = ''
      let startTime = ''
      let endTime = ''
      let startTimeStamp = ''
      let endTimeStamp = ''
      let goodsTime = [
        [],
        []
      ]
      tempAllProducts.forEach((item, index) => {
        if (index === 0) {
          tempStartTime = item.newStartTime
          tempEndTime = item.newEndTime
          tempStartTimeStamp = item.newStartTimeStamp
          tempEndTimeStamp = item.newEndTimeStamp
        } else {
          if (tempStartTimeStamp < item.newStartTimeStamp) {
            tempStartTime = item.newStartTime
            tempStartTimeStamp = item.newStartTimeStamp
          }
          if (tempEndTimeStamp > item.newEndTimeStamp) {
            tempEndTime = item.newEndTime
            tempEndTimeStamp = item.newEndTimeStamp
          }
        }
      });

      if (tempStartTimeStamp < tempEndTimeStamp) {
        // 有交集
        if (startTimeDetails > tempStartTimeStamp) {
          startTime = tempStart
          startTimeStamp = startTimeDetails
        } else {
          startTime = tempStartTime
          startTimeStamp = tempStartTimeStamp
        }
        if (endTimeDetails > tempEndTimeStamp) {
          endTime = tempEndTime
          endTimeStamp = tempEndTimeStamp
        } else {
          endTime = tempEnd
          endTimeStamp = endTimeDetails
        }
        if (startTimeStamp < endTimeStamp) {
          let goodsTimeArray = that.splitTime(date, date, 10800000, startTime, endTime)
          //营业时间小时数组
          let hourArray = []

          goodsTimeArray.forEach(ele => {
            hourArray.push(ele.slice(0, 2))
          });

          for (let j = 0; j < goodsTimeArray.length - 1; j++) {
            const eleStart = goodsTimeArray[j];
            const eleEnd = goodsTimeArray[j + 1];
            let tempData = eleStart + '-' + eleEnd
            goodsTime[0].push(tempData)
          }
          if (nowTime < startTimeStamp) {
            goodsTime[1] = goodsTime[0]
          } else if (nowTime > endTimeStamp) {
            let tempData = '无法预约自提时间'
            goodsTime[1].push(tempData)
            that.setData({
              canBuy: false
            })
          } else if (nowTime >= startTimeStamp && nowTime < endTimeStamp) {
            for (let i = 0; i < hourArray.length; i++) {
              console.log(hour)
              if (hour >= hourArray[i] && hour < hourArray[i + 1]) {
                goodsTime[1].push(time + '-' + goodsTimeArray[i + 1])
                for (let k = i + 1; k < goodsTimeArray.length - 1; k++) {
                  const eleStart = goodsTimeArray[k];
                  const eleEnd = goodsTimeArray[k + 1];
                  let tempData = eleStart + '-' + eleEnd
                  goodsTime[1].push(tempData)
                }
              }
            }
            console.log(hourArray, goodsTime[1])
          } else {
            let tempData = '无法预约自提时间'
            goodsTime[1].push(tempData)
            that.setData({
              canBuy: false
            })
          }
          tempTime[0] = that.data.multiArray[0]
          tempTime[1] = goodsTime[1]
          console.log(tempTime)
          that.setData({
            chooseTime: goodsTime,
            multiArray: tempTime,
          })
          if (tempProducts.length > 0 && that.data.type === 'dispatch') {
            let tips = ''
            if (that.data.businessStatus) {
              tips = '订单中有商品超出售卖时间~'
            } else {
              tips = '商店已打烊，不支持配送，请选择自提~'
            }
            that.setData({
              canBuy: false,
              tips: tips,
              paddingTop: '60rpx'
            })
          } else {
            let tips = ''
            that.setData({
              canBuy: true,
              tips: tips,
              paddingTop: '0'
            })
          }
        } else {
          // 无交集
          if (type === 'selftake') {
            wx.showToast({
              title: '订单内部分商品售卖时间冲突，无法下单~',
              icon: 'none',
              duration: 2000
            })
            goodsTime[0].push('无法预约自提时间')
            goodsTime[1].push('无法预约自提时间')
            tempTime[0] = that.data.multiArray[0]
            tempTime[1] = goodsTime[1]
            that.setData({
              chooseTime: goodsTime,
              multiArray: tempTime,
              canBuy: false
            })
          }
        }
      } else {
        // 无交集
        if (type === 'selftake') {
          wx.showToast({
            title: '订单内部分商品售卖时间冲突，无法下单~',
            icon: 'none',
            duration: 2000
          })
          goodsTime[0].push('无法预约自提时间')
          goodsTime[1].push('无法预约自提时间')
          tempTime[0] = that.data.multiArray[0]
          tempTime[1] = goodsTime[1]
          that.setData({
            chooseTime: goodsTime,
            multiArray: tempTime
          })
        }
      }
    }
  },
  // 预售处理商品信息列表
  handleGoodsList: function () {
    console.log("处理商品")
    const self = this
    const goodsList = self.data.goodsList
    let tempGoodsList = []
    goodsList.forEach(item => {
      let tempItem = {
        ...item,
        businessStatus: true
      }
      tempGoodsList.push(tempItem)
    })
    self.setData({
      goodsList: tempGoodsList
    })
  },
  // 弹出积分
  toScoreBox: function () {
    const self = this
    console.log(this.data.integral)
    if (this.data.couponInfo.useCoupon) {
      wx.showModal({
        title: '提示',
        content: '积分和优惠券不可同时使用',
        confirmText: '使用积分',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            self.setData({
              couponPrice: 0,
              couponInfo: {
                description: '选择优惠券',
                data: [],
                useCoupon: false
              },
              shipmentDiscount: 0,
              freeshipCoupon: 0
            })
            chooseScore()
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      if (self.data.orderType !== 'scoreMall') {
        chooseScore()
      } else {}
    }

    function chooseScore() {
      self.setData({
        integralModal: true
      })
      const score = self.data.memberScore
      const orderScore = parseInt(self.data.allPrice) * 0.1 * 100
      let available = 0
      console.log()
      if (score < orderScore) {
        available = score
      } else {
        available = orderScore
      }
      console.log(available, orderScore, self.data.allPrice, score)
      memberService.getScoreDeutible(score, self.data.allPrice, available).then(res => {
        console.log(res)
        const interval = res.scoreSpace
        const n = parseInt(res.orderAmount / interval)
        let scoreList = []
        for (let i = n; i > 0; i--) {
          const ele = i * interval;
          scoreList.push(ele)
        }
        scoreList.push(0)
        self.setData({
          scoreArray: scoreList,
        })
        let amount = parseInt(res.orderAmount / res.scoreAmount)
        let scoreAmount = res.orderAmount > amount ? res.scoreAmount : 0
        if (self.data.scoreArray.length > 1) {
          let scoreIndex = self.data.scoreIndex
          let useAmount = self.data.scoreArray[scoreIndex]
          scoreAmount = parseInt((res.orderAmount * useAmount / res.orderAmount) / amount)
        }
        let tempData = {
          ...res,
          scoreAmount: scoreAmount,
          amount: amount
        }
        self.setData({
          scoreInfo: tempData
        })
      })
    }
  },
  // 获取积分余额
  getMbrScoreBalance: function () {
    const that = this
    let mobile = ''
    if (app.globalData.userInfo.member.mobile) {
      mobile = app.globalData.userInfo.member.mobile
    } else {
      try {
        var member = wx.getStorageSync('wj_member')
        if (member) {
          mobile = member.mobile
        } else {

        }
      } catch (e) {
        // Do something when catch error
      }
    }
    memberService.getBalance(mobile).then(res => {
      that.setData({
        memberScore: res
      })
    }).catch(e => {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    })
  },

  bindScoreChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let useAmount = this.data.scoreArray[e.detail.value]
    let scoreInfo = this.data.scoreInfo
    let scoreAmount = scoreInfo.scoreAmount
    if (this.data.scoreArray.length > 1) {
      scoreAmount = parseInt((scoreInfo.orderAmount * useAmount / scoreInfo.orderAmount) / scoreInfo.amount)
    }
    scoreInfo = {
      ...scoreInfo,
      scoreAmount: scoreAmount
    }
    this.setData({
      scoreIndex: e.detail.value,
      scoreUseAmount: useAmount,
      scoreInfo: scoreInfo
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'AD5BZ-CHCKS-64OOD-6G6TX-BSOA6-IFF3V'
    });
    // 获取积分余额
    this.getMbrScoreBalance()
    // 清除缓存数据？
    try {
      // 清除缓存数据
      wx.removeStorageSync('wj_orderCardInfo')
      wx.removeStorageSync('wj_addRemarks')
      wx.removeStorageSync('wj_chooseCoupon')
    } catch (error) {

    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const self = this;
    console.log(this.options)
    if (app.globalData.storeInfo) {
      this.setData({
        storeName: app.globalData.storeInfo.name,
        storeId: app.globalData.storeInfo.id,
        storeInfo: app.globalData.storeInfo
      })
    }
    this.initializationTime() //初始化预约时间
    // 读取优惠券使用数据
    try {
      var couponData = wx.getStorageSync('wj_chooseCoupon')
      if (couponData) {
        console.log(couponData)
        let faceValue = 0
        const shipmentAmount = self.data.shipmentAmount
        let freeship = shipmentAmount
        let couponPrice = self.data.couponPrice
        let coupons = {
          freeship: [],
          discount: []
        }
        if (couponData.coupons.length > 0) {
          couponData.coupons.forEach(item => {
            if (item.coupon.function === 'FREESHIP') {
              // 运费
              let discount = parseFloat(1 - item.coupon.rate)
              faceValue = parseFloat(shipmentAmount * discount)
              freeship = parseFloat(shipmentAmount * item.coupon.rate)
              coupons.freeship.push(item)
              coupons.discount = self.data.couponInfo.data.discount
            } else {
              couponPrice = item.coupon.faceValue
              coupons.discount.push(item)
              coupons.freeship = self.data.couponInfo.data.freeship
            }
          })
        } else {
          coupons = self.data.couponInfo.data
          if (couponData.couponType === 'freeship') {
            faceValue = 0
            freeship = shipmentAmount
            coupons.freeship = []
          } else if (couponData.couponType === 'discount') {
            couponPrice = 0
            faceValue = self.data.freeshipCoupon
            freeship = self.data.shipmentDiscount
            coupons.discount = []
          }
        }
        console.log(faceValue, freeship)
        self.setData({
          freeshipCoupon: faceValue,
          shipmentDiscount: freeship,
          couponInfo: {
            description: '选择优惠券',
            data: coupons,
            useCoupon: true,
          },
          couponPrice: couponPrice
        })
      } else {

      }
      wx.removeStorageSync('wj_chooseCoupon')
    } catch (error) {

    }
    // 获取购物车数据
    try {
      var value = wx.getStorageSync('wj_shopcart')
      if (value) {
        if (value.orderType === 'group') {
          self.setData({
            goodsList: value.goodsList,
            allPrice: parseFloat(value.goodsPrice),
            teamBuyId: value.teamBuyId,
            storeId: value.storeId,
            storeName: value.storeName,
            teamLeaderRecordId: value.teamLeaderRecordId,
            orderType: 'group',
            teamBuyInfo: value.teamBuyInfo,
            type: 'selftake'
          })
          if (value.scource) {
            self.setData({
              scource: value.scource,
            })
          }
          self.initializationTime() // 初始化预约时间
          self.handleGoodsList() // 处理商品列表
        } else if (value.orderType === 'advanceSell') {
          self.setData({
            goodsList: value.goodsList,
            allPrice: parseFloat(value.allPrice),
            storeId: value.storeId,
            orderType: value.orderType,
            advanceSellInfo: {
              balanceEndTime: value.balanceEndTime,
              deliveryTime: value.deliveryTime,
              payType: value.payType,
              shipmentType: value.shipmentType
            }
          })
          if (value.scource) {
            self.setData({
              scource: value.scource,
            })
          }
        } else if (value.orderType === 'scoreMall') {
          self.setData({
            goodsList: value.goodsList,
            allPrice: parseFloat(value.allPrice),
            storeId: value.storeId,
            orderType: value.orderType,
            scoreInfo: {
              scoreAmount: value.allPrice,
            },
            integral: value.score,
            scoreUseAmount: value.score
          })
          if (value.scource) {
            self.setData({
              scource: value.scource,
            })
          }
        } else {
          self.setData({
            goodsList: value.goodsList,
            allPrice: parseFloat(value.allPrice),
            storeId: value.storeId,
            orderType: value.orderType,
            discount: parseFloat(value.discount)
          })
          if (value.scource) {
            self.setData({
              scource: value.scource,
            })
          }
          if (value.orderType === 'distribution') {
            wx.getStorage({
              key: 'wj_distributionStore',
              success: function (res) {
                self.setData({
                  storeInfo: value
                })
              }
            })
          }
        }
        // 检查商品售卖时间
        if (self.data.orderType !== 'advanceSell') {
          self.checkProductsSellTime()
        } else {
          if (value.shipmentType === 'EXPRESS') {
            self.setData({
              type: 'dispatch'
            })
          } else if (value.shipmentType === 'SELF') {
            self.setData({
              type: 'selftake'
            })
            self.initializationTime() //初始化预约时间
          }
          self.handleGoodsList() // 处理商品列表
        }
      }
    } catch (e) {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    }
    // 获取备注数据
    wx.getStorage({
      key: 'wj_addRemarks',
      success: function (res) {
        if (res.data !== '') {
          self.setData({
            remarks: res.data
          })
        } else {

        }
      }
    })
    // 获取会员信息
    wx.getStorage({
      key: 'wj_member',
      success: function (res) {
        self.setData({
          memberInfo: res.data
        })
      }
    })
    // 读取储值余额使用信息
    wx.getStorage({
      key: 'wj_orderCardInfo',
      success: function (res) {
        self.setData({
          cardInfo: {
            balance: res.data.balance,
            password: res.data.password,
            useAmount: res.data.useAmount,
          },
          useReserve: res.data.useReserve,
        })
      }
    })
    // 检查参数中是否有配送方式
    if (this.options.type) {
      let typeData = JSON.parse(this.options.type)
      console.log(typeData)
      self.setData({
        type: typeData
      })
    }

    // 检查配送距离
    if (self.data.type === 'dispatch') {
      this.checkDistribution()
    } else {}
    // 获取分享人id
    wx.getStorage({
      key: 'wj_sharingId',
      success: function (res) {
        if (res.data && res.data !== '' && res.data !== undefined)
          self.setData({
            sharingPersonId: res.data
          })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    try {
      // 清除缓存数据
      wx.removeStorageSync('wj_orderCardInfo')
      wx.removeStorageSync('wj_addRemarks')
      wx.removeStorageSync('wj_chooseCoupon')
    } catch (error) {

    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})